package com.foreverwin.jzymes.framework.websocket;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Configuration
public class WebSocketConfig {

    @Value("${mes.websocket.server.port}")
    private int serverPort;

    @Value("${mes.websocket.contextPath}")
    private String contextPath;

    private Server server;

    @PostConstruct
    public void startServer(){
        try {
            // Creating Jetty Server on 8081 port
            server = new Server( serverPort );

            // Registerring WebSocketServer in Jetty server
            WebSocketServer chatWebSocketHandler = new WebSocketServer();
            chatWebSocketHandler.setHandler(new DefaultHandler());

            ContextHandler contextHandler = new ContextHandler();
            contextHandler.setContextPath( contextPath );
            contextHandler.setHandler( chatWebSocketHandler );

            server.setHandler(chatWebSocketHandler);
            // Starting jetty
            server.start();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void destroy(){
        try{
            if( server != null ){
                server.stop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
